# from https://gist.github.com/739049

from django.forms.widgets import Input
from django.utils.safestring import mark_safe
from django.conf import settings

class GoogleMapWidget(Input):
    input_type = 'hidden'
    """
    Widget to display a Google Map on a page with the ability to move a marker
    around and fetch coordinates.
    """
    class Media:
        js = (
            'http://maps.google.com/maps/api/js?sensor=false&key=%s' % settings.MAP_API_KEY,
            'googlemap_location.js',
        )

    def render(self, name, value, attrs=None):
        """
        Attribute extras:
            width: width of the Google Map in pixels or percent. Must be the full string.
            height: height of the Google Map in pixels or percent. Must be the full string.
            markerMovedCallback: incase we don't want to populate the two default fields, let them specify their own callback.
            center: (lat, lng) coordinates in tuple format. If not provided, will auto-detect location if available.
            geolocate: Boolean. Default = True, If False, will not do any geolocation. Should be set to False if you provide a center() attribute
                    you do not want potentially over-ridden.
        """

        # Defaults, can be overriden by any same-key passed through `attrs`
        final_attrs = self.build_attrs(attrs)

        if value.find(',') > 0:
            (lat, lng) = value.split(',')
        else:
            (lat, lng) = ('null', 'null')

        context = {
            'width': '600px',
            'height': '300px',
            'markerMovedCallback': 'function(point) { jQuery("#%s").val(point.lat() + "," + point.lng()); }' % final_attrs['id'],
            'lat': lat,
            'lng': lng,
            'geolocate': 'true',
        }
        context.update(final_attrs)

        if 'center' in final_attrs:
            context['lat'], context['lng'] = final_attrs['center']

        final_attrs.update({'class': 'vTextField'})

        context.update({ 
            'input': super(GoogleMapWidget, self).render(name, value, final_attrs),
        })
        html = u'''
        %(input)s
        <input type='text' style='width: 400px;' id='map_search_text' /> <input type='button' id='map_search' value='Search' />
        <div id="map_canvas" style='width: %(width)s; height: %(height)s;'></div>
        <div id="map_message">Marker has been placed near the coordinates of your current location. Please adjust it to match the Places location.</div>
        <script type="text/javascript">
            //<![CDATA[
            var call_google_map = function(jQuery) {
                google_map_location.init({
                    'jQuery': jQuery,
                    markerMovedCallback: %(markerMovedCallback)s,
                    lat: %(lat)s,
                    lng: %(lng)s,
                    geolocate: %(geolocate)s
                });

                // Add some event handlers for our search box.
                jQuery("#map_search").click(function() {
                    google_map_location.codeAddress(jQuery("#map_search_text"));
                });

                jQuery("#map_search_text").keypress(function(e) {
                    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                        google_map_location.codeAddress(jQuery(this));
                        return false;
                    }
                });
            }

            // Do a simple check to see if we're using this widget in the admin.
            if (typeof django != 'undefined') {
                (function($) {
                    call_google_map($);
                })(django.jQuery);
            } else {
                call_google_map($);
            }
            //]]>
        </script>
        ''' % context

        return mark_safe(html)
